import logging
import random
from flask import abort
import re
from flask import make_response
from iHome import redis_store
from iHome.api_1_0 import api
from flask import request,current_app,jsonify
from iHome.utils.captcha.captcha import captcha
# from iHome.libs.yuntongxun.sms import CCP
from iHome.utils.response_code import *
import json
from iHome.models import User

from iHome import constants






@api.route('/imagecode')
def generate_image_code():

    '''
    1.获取传入的验证码编号,并编号是否存在
    2.生成图片验证码
    3.保存编号和其对应的图片验证码内容到redis
    4.返回验证码图片

    '''

    current_app.logger.error("error log")
    #1.获取传入的验证码编号, 并编号是否存在

    cur = request.args.get('cur')
    pre = request.args.get('pre')


    if not cur:
        abort(403)


    #2.生成图片验证码
    name,text,content = captcha.generate_captcha()


    #    3.保存编号和其对应的图片验证码内容到redis
    try:
        #删除之前保存的数据

        redis_store.delete('ImageCode_'+pre)
        redis_store.set('ImageCode_'+cur,text,constants.IMAGE_CODE_REDIS_EXPIRES)


    except Exception as e:
        current_app.logger.error(e)

        #保存出现错误
        return jsonify(errno = RET.DBERR,errmsg = '保存验证码失败')


    #4.返回验证码图片

    response = make_response(content)

    response.headers['Content-Type'] = 'image/jpg'
    return response


@api.route('/smscode',methods=['POST'])
def send_sms():
    """
    1.接受参数并判断是否有值
    2.检验手机号是否正确
    3.通过传入的图片去redis中查询真正的图片验证码内容
    4.进行检验内容比对
    5.生成发送短信验证码内容并发送短信
    6.redis中保存短信验证码内容
    7.返回发送成功
    :return:
    """
    #1.接受参数并判断是否有值
    data = request.data

    data_dict = json.loads(data.decode())

    mobile = data_dict.get('mobile')
    image_code = data_dict.get('image_code')
    image_code_id = data_dict.get('image_code_id')

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        logging.error(e)
    else:

        if user is not None:
            return jsonify(errno=RET.DBERR, errmsg='该手机已注册')


    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    #2.检验手机号是否正确
    if not re.match(r'^1[3578]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机格式不正确')

    #3.通过传入的图片去redis中查询真正的图片验证码内容
    try:
        real_image_code = redis_store.get('ImageCode_%s' % image_code_id).decode()

        if real_image_code:
             redis_store.delete('ImageCode_%s' % image_code_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取图片验证码失败')

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='图片验证码已过期')

   #4.进行检验内容比对
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='图片验证码错误')

    #5.生成发送短信验证码内容并发送短信
    sms_code = '%06d' % random.randint(0, 99999)
    current_app.logger.info("图片验证码内容为: %s" % sms_code)

    # try:
    #     res = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)
    #
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.THIRDERR, errmsg='发送短信验证码失败')

    # if res != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg='发送短信验证码失败')

    try:
        print('SMS_%s' % mobile)
        redis_store.set('SMS_%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存图片验证码失败')
    data = {
        'sms_code':sms_code
    }
        # 7. 返回应答，发送短信成功
    return jsonify(data=data,errno=RET.OK, errmsg='发送短信验证码成功')
